// const axios = require("axios");
const puppeteer = require("puppeteer");
console.log("微信");
// async function getHttp() {
//   try {
//     // const response = await axios.get("http://47.119.187.195:3000");
//     const response = await axios.get("http://47.119.187.195:5500/index.html");
//     console.log(response.data); // 获取到的网页 HTML 内容
//   } catch (error) {
//     console.error("请求失败:", error);
//   }
// }
async function getPuppeteer(url) {
  // const browser = await puppeteer.launch()
  const browser = await puppeteer.launch({
    // executablePath: "C:/Program Files/Google/Chrome/Application/chrome.exe",
    executablePath: "./chrome/chrome.exe",
    // headless: false, // 打开浏览器以便调试
    // devtools: true, // 启用开发者工具
  });
  const page = await browser.newPage();
  page.on("requestfailed", (request) => {
    console.error(`请求失败: ${request.url()}`);
  });
  await page.goto(url);
  // 选择 id="fakeWechatMoment" 的元素
  const element = await page.$("#fakeWechatMoment");
  const content = await page.content(); // 获取最终渲染的 HTML 内容
  // console.log(content)

  if (element) {
    // 获取元素的尺寸和位置
    const boundingBox = await element.boundingBox();

    /**-
     * 保存截图
     */
    if (boundingBox) {
      // 截取该元素部分图片保存为screenshot6.png
      // await page.screenshot({
      //   path: "screenshot6.png",
      //   clip: {
      //     x: Math.round(boundingBox.x),
      //     y: Math.round(boundingBox.y),
      //     width: Math.round(boundingBox.width),
      //     height: Math.round(boundingBox.height),
      //   },
      // });

      /** 截取该元素部分并获取 Base64 图片*/
      const base64Image = await page.screenshot({
        path: "screenshot.png",
        clip: {
          x: Math.round(boundingBox.x),
          y: Math.round(boundingBox.y),
          width: Math.round(boundingBox.width),
          height: Math.round(boundingBox.height),
          // height: 2080,
        },
        encoding: "base64", // 设置编码为 Base64
      });
      // 保存截图到本地
      // const filePath = "screenshot7.png";
      // fs.writeFileSync(filePath, screenshotBuffer);

      // console.log("Base64 图片:", base64Image);
      // console.log('成功截取 id="fakeWechatMoment" 的部分');
      return base64Image;
    } else {
      console.log("无法获取元素的边界框");
    }
  } else {
    console.log('未找到 id="fakeWechatMoment" 的元素');
  }

  //  // 截图
  // await page.screenshot({ path: "screenshot4.png", fullPage: true });
  // await page.screenshot({ path: "screenshot2.png" });
  console.log(21111);
  await browser.close();
  return ''

}
module.exports = {
  getPuppeteer,
};
